<script setup>
import { ref, reactive } from 'vue'
import { getUserOrderListApi, addCommentApi, getUserCommentApi } from '@/api/user'
import { ElMessage } from 'element-plus';
import { useTokenStore } from '@/store/token'

// 获取登录用户信息
const tokenStore = useTokenStore();

//  订单列表
const orderList = ref([])
const pageOrderList = ref([]); // 当前页的数据（用于显示）
// 获取用户订单列表
function getUserOrders() {
  const userId = tokenStore.user.userId
  console.log(userId);
  getUserOrderListApi(userId).then(res => {
    console.log(res);
    if (res.code === 0) {
      orderList.value = res.data
      total.value = orderList.value.length
      pagePages.value = Math.ceil(total.value / pageSize.value); // 计算总页数
      updatePaginatedList();   // 更新分页数据
    } else {
      ElMessage.error(res.message)
    }
  })
}
getUserOrders();

//分页
const total = ref(0); // 总条数
const pagePages = ref(1); // 总页数
const currentPage = ref(1); // 当前页码
const pageSize = ref(3);  // 每页显示条数

// 更新分页数据（根据 currentPage 和 pageSize）
const updatePaginatedList = () => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  pageOrderList.value = orderList.value.slice(start, end);  // 切割出当前页的数据
};

// 处理每页条数变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize; // 更新每页显示的条目数
  updatePaginatedList();  // 更新分页数据
};

// 处理当前页码变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage; // 更新当前页码
  updatePaginatedList();  // 更新分页数据
};

// 评价模态框控制
const evaluateDialog = ref(false)
const viewEvaluationDialog = ref(false);
// 查看评价
const viewEvaluationForm = reactive({
  rating: 0,
  content: '',
  createTime:''
});

// 评价数据
const evaluateForm = reactive({
  orderId: '',
  userId: '',
  rating: 0,
  content: ''
});

// 评价规则
const evaluateRules = {
  evaluate: [
    { required: true, message: '请输入评价', trigger: 'blur' },
    { min: 1, max: 100, message: '长度在 1 到 200 个字符', trigger: 'blur' }
  ]
}

// 打开评论弹窗
function evaluate(userId, goodId) {
  evaluateForm.userId = userId;
  evaluateForm.goodId = goodId;
  evaluateDialog.value = true;
}

//提交评价
function submit() {
  console.log(evaluateForm);
  
  // 提交评价
  addCommentApi(evaluateForm).then(res => {
    if (res.code === 0) {
      ElMessage.success('评价成功');
      getUserOrders();
    } else {
      ElMessage.error(res.message);
    }
  })
  // 关闭模态框
  evaluateDialog.value = false;
}


// 查看评价
function viewEvaluation(commentId) {
  // 获取评价
  getUserCommentApi(commentId).then(res => {
  console.log(res);
  
  if (res.code === 0) {
    viewEvaluationForm.rating = res.data.rating
    viewEvaluationForm.content = res.data.content
    viewEvaluationForm.createTime = res.data.createTime
  } else {
    ElMessage.error(res.message)
  }
  viewEvaluationDialog.value = true;
  })
}
</script>

<template>
<el-card class="page-container">
    <p class="header">订单管理</p>
    <div style="overflow-y: auto; height: 640px;">
      <ul v-for="item in pageOrderList" :key="item.orderId" class="course">
        <li>
          <div class="good-item">
            <img :src="item.goods.images">
            <div class="text-box">
              <li><p class="title">{{ item.goods.goodName }}</p></li>
              <li><p class="desc">{{ item.orderNum }}</p></li>
              <li class="price-box"><span class="amount">x{{ item.amount }}</span><span class="price">&yen;{{ item.payment }}</span></li>
              <li class="desc">{{ item.payTime }}</li>
            </div>
            <div class="right">
              <el-button v-if="!item.comment.commentId"  @click="evaluate(item.userId,item.goodId)" type="primary">去评价</el-button>
              <el-button v-else @click="viewEvaluation(item.comment.commentId)" type="primary">查看评价</el-button>
            </div>
        </div>
        </li>
      </ul>
    </div>
      <!--分页区域-->
      <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[3]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="sizes,prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            style="position: absolute ;bottom: 30px; margin-top: 30px; margin-left: 20%;"
        />
</el-card>


<!-- 评价模态框 -->
  <el-dialog title="评价" v-model="evaluateDialog" width="40%">
  <el-form :model="evaluateForm" ref="evaluateFormRef" :rules="evaluateRules">
    <el-form-item label="评价星级" prop="star">
      <el-rate v-model="evaluateForm.rating" :max="5" :colors="['#99A9BF', '#F7BA2A', '#FF9900']" :low-threshold="1" :high-threshold="5" show-score></el-rate>
    </el-form-item>
    <el-form-item label="评价内容" prop="content">
      <el-input v-model="evaluateForm.content" type="textarea" :rows="5"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button @click="submit" type="primary">提交</el-button>
    </el-form-item>
  </el-form>
  </el-dialog>

  <el-dialog title="查看评价" v-model="viewEvaluationDialog" width="40%">
    <el-form :model="viewEvaluationForm" width="40%">
        <el-form-item label="评价星级" prop="star">
          <el-rate v-model="viewEvaluationForm.rating" :max="5" :colors="['#99A9BF', '#F7BA2A', '#FF9900']" :low-threshold="1" :high-threshold="5" show-score disabled></el-rate>
        </el-form-item>
        <el-form-item label="评价内容" prop="content">
          <el-input v-model="viewEvaluationForm.content" type="textarea" :rows="4" readonly></el-input>
        </el-form-item>
        <div>
          <span class="desc">评价时间：{{ viewEvaluationForm.createTime }}</span>
        </div>
      </el-form>
  </el-dialog>

</template>
  

  <style lang="scss" scoped>

  .page-container {
    min-height: 100%;
    box-sizing: border-box;
    position: relative;
  
    .header {
      font-size: 22px;
      margin-bottom: 10px;
    }
  }

  .course {
    padding: 0; /* 去掉默认的内边距 */
    list-style-type: none; /* 去掉默认的列表样式 */
    align-items: center; /* 垂直居中对齐 */

    .good-item {
      padding: 10px;
      display: flex;
      align-items: center;
      position: relative;
      width: 100%;
      border-bottom: 1px solid #d8d8d8;
      img{
        width: 120px;
        height: 120px;
      }
      .text-box{
        margin-left: 20px;
        li{
          margin-bottom: 5px;
        }
        .title{
          font-size: 18px;
        }
        .desc {
          color: #999;
        }
        .amount{
          color: #999;
        }
        .price {
          color: $priceColor;
          font-size: 20px;
        }
        .amount{
          margin-right: 10px;
        }
        }
        .right{
          position: absolute;
          right: 20px;
          bottom: 20px;
        }
    }
  }
</style>
  